#include "modbusmanger.h"
#include "ui_modbusmanger.h"
#include <typeinfo>
#include <QMutexLocker>
#include <QReadLocker>
#include <QWriteLocker>
#include <QReadWriteLock>
#include<mutex>
#include "maininterface.h"
#include "monitordevice.h"
#include"manualcontrol.h"
#include"pidcontroller.h"
using namespace std;
Q_GLOBAL_STATIC(ModBusManger,theInstance)
int ModBusManger::  sensorDataCount =0;
int ModBusManger:: locationCount=0;
ModBusManger::ModBusManger(QWidget *parent) :
    QDialog(parent),m_retryCount(0), m_maxRetries(3),ui(new Ui::ModBusManger)
  {
    ui->setupUi(this);
    //    initModbusDevice();
    //    checkSerialPortExist();
    //    connectDevice();
    //    readModsimData();
    //初始化modbus设备
    initModbusDevice();
    modBusDeviceStatus=isconnectDevice();//判读是否连接
    checkSerialPortExist();//检查串口
    isProcessing = false;
    IsProcessing = false;
    QTimerReadModsimData();
    //控制空气温度
    connect(ManualControl::instance(),&ManualControl::sendRaiseAirTemperature,this,&ModBusManger::setAirTemperature);
    connect(ManualControl::instance(),&ManualControl::sendCloseHeatingEquipment,this,&ModBusManger::resetAlarmIndexAndData);
    connect(ManualControl::instance(),&ManualControl::sendReduceAirTemperature,this,&ModBusManger::setAirTemperature);
    connect(ManualControl::instance(),&ManualControl::sendCloseReduceEquipment,this,&ModBusManger::resetAlarmIndexAndData);
    //控制空气湿度
    connect(ManualControl::instance(),&ManualControl::sendOpenIrrigationEquipment,this,&ModBusManger::setAirHumidity);
    connect(ManualControl::instance(),&ManualControl::sendCloseIrrigationEquipment,this,&ModBusManger::resetAlarmIndexAndData);
    connect(ManualControl::instance(),&ManualControl::sendOpenVentilatingEquipmentG2_1,this,&ModBusManger::setAirHumidity);
    connect(ManualControl::instance(),&ManualControl::sendCloseVentilatingEquipmentG2_1,this,&ModBusManger::resetAlarmIndexAndData);
   //控制CO2浓度
    connect(ManualControl::instance(),&ManualControl::sendOpenCO2InterpolatorEquipment_G3,this,&ModBusManger::setCO2);
    connect(ManualControl::instance(),&ManualControl::sendCloseCO2InterpolatorEquipment_G3,this,&ModBusManger::resetAlarmIndexAndData);
    connect(ManualControl::instance(),&ManualControl::sendOpenVentilatingEquipmentG2_2,this,&ModBusManger::setCO2);
    connect(ManualControl::instance(),&ManualControl::sendCloseVentilatingEquipmentG2_2,this,&ModBusManger::resetAlarmIndexAndData);
   //控制Light强度
    connect(ManualControl::instance(),&ManualControl::sendOpenLightingEquipment_G5,this,&ModBusManger::setLight);
    connect(ManualControl::instance(),&ManualControl::sendCloseLightingEquipment_G5,this,&ModBusManger::resetAlarmIndexAndData);
    connect(ManualControl::instance(),&ManualControl::sendOpenRollUpDoorEquipment_G4,this,&ModBusManger::setLight);
    connect(ManualControl::instance(),&ManualControl::sendCloseRollUpDoorEquipment_G4,this,&ModBusManger::resetAlarmIndexAndData);
   //控制土壤湿度
    connect(ManualControl::instance(),&ManualControl::sendOpenIrrigationEquipmentG1_2,this,&ModBusManger::setSoilH);
    connect(ManualControl::instance(),&ManualControl::sendCloseIrrigationEquipmentG1_2,this,&ModBusManger::resetAlarmIndexAndData);
    connect(ManualControl::instance(),&ManualControl::sendOpenVentilatingEquipmentG2_3,this,&ModBusManger::setSoilH);
    connect(ManualControl::instance(),&ManualControl::sendCloseVentilatingEquipmentG2_3,this,&ModBusManger::resetAlarmIndexAndData);
    //自动控制温度
    connect(PidController::instance(),&PidController::sendAutoControlAirTemperature,this,&ModBusManger::autoSetAirTemperature);
   //自动控制光强
    connect(PidController::instance(),&PidController::sendAutoControlLightIntensity,this,&ModBusManger::autoSetLight);
   //自动控制空气湿度
    connect(PidController::instance(),&PidController::sendAutoControlAirHumidity,this,&ModBusManger::autoSetAirHumidity);
   //自动控制CO2浓度
   connect(PidController::instance(),&PidController::sendAutoControlCO2Concentration,this,&ModBusManger::autoSetCO2);
   //自动控制土壤湿度
   connect(PidController::instance(),&PidController::sendAutoControlSoilMoisture,this,&ModBusManger::autoSetSoilH);
}






ModBusManger::~ModBusManger()
{
    delete ui;
}

ModBusManger *ModBusManger::instance()
{
    return theInstance();
}

void ModBusManger::getSensorDataSet()
{


    qDebug()<<"sensorDataCount"<<sensorDataCount;
}

void ModBusManger::sendSensorDataSet()
{

}

void ModBusManger::disConnectDevice()
{
    if (modbusDevice)//断联设备
    {
        modbusDevice->disconnectDevice();
//        delete modbusDevice;
        modBusDeviceStatus=false;

    }

    if (m_timer->isActive())//关闭定时器
    {
        m_timer->stop();
    }
    qDebug()<<"断开连接";

}

void ModBusManger::reConnectDevice()
{
    initModbusDevice();
    modBusDeviceStatus=isconnectDevice();//判读是否连接
    if (!m_timer->isActive())//关闭定时器
    {
        m_timer->start();
    }
  qDebug()<<"重新连接";

}

bool ModBusManger::getModBusDeviceStatus()
{
    return modBusDeviceStatus;
}

void ModBusManger::initModbusDevice()//对modbus进行初始化
{
    // 先判断modbusDevice是否连接
    if (modbusDevice)
    {
        modbusDevice->disconnectDevice();
        delete modbusDevice;
    }

    // 1. 创建Modbus RTU主站设备
    modbusDevice = new QModbusRtuSerialMaster(this);
    // 2. 配置串口参数（需与ModSim完全一致）
 extern int serialPortOpenMode;
if(!serialPortOpenMode)
{
    portName = "COM2"; // 修改为实际串口号（如COM2、/dev/ttyUSB0
    modbusDevice->setConnectionParameter(QModbusDevice::SerialPortNameParameter, portName);
    modbusDevice->setConnectionParameter(QModbusDevice::SerialBaudRateParameter, QSerialPort::Baud9600);
    modbusDevice->setConnectionParameter(QModbusDevice::SerialDataBitsParameter, QSerialPort::Data8);
    modbusDevice->setConnectionParameter(QModbusDevice::SerialParityParameter, QSerialPort::NoParity);
    modbusDevice->setConnectionParameter(QModbusDevice::SerialStopBitsParameter, QSerialPort::OneStop);


}
else if(serialPortOpenMode)
{

//手动配置
extern serialPortBolock serialPortBolockData[2];
modbusDevice->setConnectionParameter(QModbusDevice::SerialPortNameParameter, serialPortBolockData[0].PotrName);
modbusDevice->setConnectionParameter(QModbusDevice::SerialBaudRateParameter, serialPortBolockData[0].Baudrate);
modbusDevice->setConnectionParameter(QModbusDevice::SerialDataBitsParameter, serialPortBolockData[0].DataBits);
modbusDevice->setConnectionParameter(QModbusDevice::SerialParityParameter, serialPortBolockData[0].Parity);
modbusDevice->setConnectionParameter(QModbusDevice::SerialStopBitsParameter, serialPortBolockData[0].StopBits);




}











}

bool ModBusManger::checkSerialPortExist()
{


    // 3. 检查串口是否存在
    bool portAvailable = false;
    const auto ports = QSerialPortInfo::availablePorts();
    for (const QSerialPortInfo &port : ports)
    {
        if (port.portName() == portName)
        {
            portAvailable= true;
            qDebug()<<"portName:"<<portName<<"存在"<<endl;
            break;
        }
    }
    if (!portAvailable) {
        qDebug() << "错误：串口" << portName << "不存在！";
        QCoreApplication::exit(-1);
        qDebug()<<"portName:"<<portName<<"不存在"<<endl;
        return portAvailable;
    }
    else
    {
        return portAvailable;
    }

}

bool ModBusManger::isconnectDevice()
{

    if (!modbusDevice->connectDevice()) {
        qDebug() << "连接失败：" << modbusDevice->errorString();
        qDebug() << "可能原因：串口被占用、权限不足或参数错误";

        QCoreApplication::exit(-1);



        return false;
    }

    qDebug() << "成功连接到串口" << portName;

    return true;




}

void ModBusManger::readModsimData()
{


    // 构造请求：功能码0x03，起始地址0（对应ModSim的40001），读取5个寄存器
    if(modBusDeviceStatus)
    {

        QModbusDataUnit  request(QModbusDataUnit::HoldingRegisters, 0, 5);//构建请求格式
        QModbusReply *reply;


              reply = modbusDevice->sendReadRequest(request, 1);//请求
//              isProcessing=true;




//        replyQueue.enqueue(reply);
//        QModbusReply *temp=replyQueue.head();
        // 发送请求到从站地址1
        if (reply) {
            connect(reply, &QModbusReply::finished, this, &ModBusManger::onReadFinished);
            connect(reply, &QModbusReply::errorOccurred, this, &ModBusManger::onModbusError);
        }
        else {
            qDebug() << "发送请求失败：" << modbusDevice->errorString();
            QCoreApplication::exit(-1);
        }



    }








}

void ModBusManger::startPolling()
{

//    bool isProcessing=false;=isPolling;
    if (IsProcessing)
    {
            qDebug() << "已有请求在处理，跳过本次轮询";
            return;
    }
    if (modbusDevice->state() != QModbusDevice::ConnectedState) {
        qDebug() << "设备未连接";
        return;
    }

    IsProcessing= true; // 标记为轮询中
//if(!locationCount)
//{
//   isProcessing=false;

//}
//else
//{

//isProcessing=true;
//qDebug()<<"isProcessing-------------------->"<<isProcessing;
//}


    // 构造请求：读取保持寄存器0（40001）开始的5个寄存器
    QModbusDataUnit request(QModbusDataUnit::HoldingRegisters, 0, 5);
    QModbusReply *reply;
//        requestQueue.enqueue(request);
    //if(!isProcessing)
    //{
     reply= modbusDevice->sendReadRequest(request, 1);
     if (reply)
     { // 从站地址1
         // 2. 设置超时检测（例如 3000ms）
         timeoutTimer = new QTimer(reply); // 将计时器绑定到 reply，自动释放
         timeoutTimer->setSingleShot(true);        // 单次触发
         timeoutTimer->start(3000);
         connect(reply, &QModbusReply::finished, this, &ModBusManger::onReadFinished2);

         // connect(reply,&QModbusReply::finished,this,&ModBusManger::onReadFinished2);
         connect(reply, &QModbusReply::errorOccurred, this, &ModBusManger::onModbusError2);


     }
     else
     {


         QObject::connect(timeoutTimer, &QTimer::timeout, [reply]() {
                 if (!reply->isFinished()) {
                     qWarning() << "Request timed out!";
                    //reply->abort();      // 终止未完成的请求
                     reply->deleteLater(); // 必须释放资源
                 }
             });





         qDebug() << "发送请求失败：" << modbusDevice->errorString();

//         if(handleRequestError())
//         {


//         }
//         else{

//             reply->deleteLater();
//         }



     }

  //  }

          /*replyQueue.enqueue(reply);*/////-------------------------------------------------------



}



void ModBusManger::testSensorData()
{

qDebug()<<"--------------------------------------------"<<endl;
for(QVector<sensorData>:: iterator it=sensorDataSet.begin();it!=sensorDataSet.end();it++)
{
qDebug()<<"测试"<<endl;
qDebug()<<"Time"<<it->Time<<endl;
qDebug()<<"AirTemperature;"<<it->AirTemperature<<endl;
qDebug()<<"AirHumidity"<<it->AirHumidity<<endl;
qDebug()<<"LightIntensity"<<it->LightIntensity<<endl;
qDebug()<<"CO2Concentration"<<it->CO2Concentration<<endl;
qDebug()<<"SoilMoisture"<<it->SoilMoisture<<endl;

}
qDebug()<<"--------------------------------------------"<<endl;
}
void ModBusManger::onReadFinished()
{
    QModbusReply *reply = qobject_cast<QModbusReply *>(sender());
    if (!reply) return;
    if (reply->error() == QModbusDevice::NoError)
    {   /*isPolling=false;*/
        const QModbusDataUnit data = reply->result();
        qDebug() << "读取成功：";
        for (int i = 0; i < data.valueCount(); ++i)
        {
            qDebug() << "寄存器地址" << data.startAddress() + i + 40001
                     << "的值：" << data.value(i);

        }

    }
    else
    {
        qDebug() << "读取错误：" << reply->errorString();
    }

    //    reply->deleteLater();
    //    modbusDevice->disconnectDevice();
    //    QCoreApplication::quit();
}

void ModBusManger::onModbusError(QModbusDevice::Error error)
{
    qDebug() << "Modbus错误：" << error;
    modbusDevice->disconnectDevice();
    QCoreApplication::quit();
}

void ModBusManger::QTimerReadModsimData()
{
    // 启动定时轮询（首次立即执行，后续每1秒一次）


    QTimer::singleShot(0, this, &ModBusManger::startPolling);
    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &ModBusManger::startPolling);
    m_timer->start(1000); // 1秒间隔


}

void ModBusManger::onReadFinished2()
{
    timeoutTimer->stop();
    QModbusReply *reply = qobject_cast<QModbusReply *>(sender());
    sensorData SenData;
    if (!reply)
    {

        reply->deleteLater();
        reply = nullptr;
        IsProcessing =false;
//        isProcessing=false;
//        modbusDevice->disconnectDevice();
        return;
    }

    if (reply->error() == QModbusDevice::NoError) {
         // 请求完成后重置标志

        const QModbusDataUnit data = reply->result();
        SenData.Time=QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
 //  qDebug() << "[" <<QDateTime::currentDateTime().toString("hh:mm:ss") << "] 数据更新：";

//         qDebug()<<"data.valueCount"<<data.valueCount();

        for (int i = 0,n=0; i < data.valueCount(); ++i)
        {
//            qDebug() << "  寄存器" << data.startAddress() + i + 40001
//                     << "=" << data.value(i);
//            quint16 temp=data.value(i);
//            qDebug()<<"typeid——data.value():"<<typeid (data.value(i)).name();
//            qDebug()<<"typeid-temp:"<<typeid (temp).name();
           // QString temp = QString::number(data.value(i));
             int temp=data.value(i) ;

            //qDebug()<<sizeof(data.value(da));
            switch(i)
            {
            case 0:
                SenData.AirTemperature=temp;
                break;
            case 1:
                SenData.AirHumidity=temp;
                break;

            case 2:
                SenData.LightIntensity=temp;
                break;
            case 3:
                SenData.CO2Concentration=temp;
                break;
            case 4:
                SenData.SoilMoisture=temp;
                break;

            }

        }

        extern QVector<sensorData>globalSensorData;
        extern QVector<sensorData>globalSensorData2;
        extern int totalCount;
        extern int totalCount2;
        globalSensorData.push_back(SenData);
        globalSensorData2.push_back(SenData);
        totalCount=globalSensorData.count();
        totalCount2=totalCount;

        sensorDataSet.push_back(SenData);//用来存储从modsim获取的数据
        //userMysql::instance()->saveSensorData(SenData);
        UserMysqlS::instance()->saveSensorData(SenData);
       extern bool DynamicCurveStatus;
        if(DynamicCurveStatus)
        {
            emit sendDynamicCurve();
            qDebug()<<"emit sendDynamicCurve();";
        }

        MonitorDevice::instance()-> MonitorSensorDataFunction(SenData);
        sensorDataCount++;
        if(globalSensorData.count()>500)
            emit GlobalSensorDataIsChanged();


        m_retryCount = 0; // 成功时重置重试计数器
       //testSensorData();

    }
    else
    {
        qDebug() << "读取错误：" << reply->errorString();

        //handleRequestError();

    }

    reply->deleteLater();
    reply = nullptr;
//    isPolling = false;
//    isProcessing=false;
     IsProcessing =false;
}

void ModBusManger::onModbusError2(QModbusDevice::Error error)
{
    qDebug() << "Modbus协议错误：" << error;
   // handleRequestError();
//     isPolling = false;
}

void ModBusManger::handleConnectionError()
{
    qDebug() << "连接失败：" << modbusDevice->errorString();
    if (++m_retryCount <= m_maxRetries) {
        qDebug() << "尝试重新连接（" << m_retryCount << "/" << m_maxRetries << ")...";
        QTimer::singleShot(5000, this, &ModBusManger::reConnectModbusDevice); // 5秒后重连
    } else {
        qCritical() << "达到最大重试次数，停止连接尝试！";
        QCoreApplication::quit();
    }
}

bool ModBusManger::handleRequestError()
{
   bool ok=false;
    if (++m_retryCount <= m_maxRetries) {
        qDebug() << "请求错误，等待重试（" << m_retryCount << "/" << m_maxRetries << ")...";

    }
    else {
        qCritical() << "达到最大错误次数，重新初始化连接...";
        m_retryCount = 0;
       ok=reConnectModbusDevice();
    }
    return ok;
}

bool ModBusManger::reConnectModbusDevice()
{
    initModbusDevice();
    return isconnectDevice();


}

void ModBusManger::modificationGlobalSensorData()
{

//修改全局数据
// extern QVector<sensorData>globalSensorData;
// extern QReadWriteLock readerWriteMutex;
// QWriteLocker locker(&readerWriteMutex); //修改数据加写锁
// sensorData temp =globalSensorData.p;

}



void ModBusManger::on_pushButtonCancel_clicked()
{

   this->close();
}


void ModBusManger::on_pushButtonConfirm_clicked()
{





}

void ModBusManger::setAirTemperature(int step)//设置温度的函数step为+加温为-降温
{
extern QVector<sensorData> globalSensorData2;
extern int totalCount2;
 AlarmIndex.Index_AirT++;
 if(AlarmIndex.Index_AirT==1)
 {
     if(totalCount2 > 1)
     {
          AlarmData.Data_AirT=globalSensorData2[totalCount2-1].AirTemperature;
     }

     qDebug()<<"AlarmData.Data_AirT:"<<AlarmData.Data_AirT<<endl;
 }

 int tempData=AlarmData.Data_AirT+step*AlarmIndex.Index_AirT;
 QModbusDataUnit request(QModbusDataUnit::HoldingRegisters, 0, 1);
 request.setValue(0,tempData);
 QModbusReply* reply = modbusDevice->sendWriteRequest(request, 1);
 if (!reply)
 {
     qDebug() << "请求发送失败";
    // QMessageBox::information(this,"faild","请求发送失败！");

 }
 // 处理响应
 connect(reply, &QModbusReply::finished, [reply,this]()
 {
     if (reply->error() == QModbusDevice::NoError)
     {
         qDebug() << "写入成功yyy！";
         //QMessageBox::information(this,"success","写入成功！");



     } else
     {
         qDebug() << "错误：" << reply->errorString();
       //  QMessageBox::information(this,"faild","失败！");

     }
     reply->deleteLater();
 });



}

void ModBusManger::setAirHumidity(int step)
{

        extern QVector<sensorData> globalSensorData2;
        extern int totalCount2;
         AlarmIndex.Index_AirH++;
         if(AlarmIndex.Index_AirH==1)
         {
             if(totalCount2 > 1)
             {
                  AlarmData.Data_AirH=globalSensorData2[totalCount2-1].AirHumidity;
             }

             qDebug()<<"AlarmData.Data_AirH:"<<AlarmData.Data_AirH<<endl;
         }

         int tempData=AlarmData.Data_AirH+step*AlarmIndex.Index_AirH;
         qDebug()<<"tempData"<<AlarmIndex.Index_AirH<<":"<<tempData<<endl;
         QModbusDataUnit request(QModbusDataUnit::HoldingRegisters,1,1);
         request.setValue(0,tempData);
         QModbusReply* reply = modbusDevice->sendWriteRequest(request, 1);
         if (!reply)
         {
             qDebug() << "请求发送失败";
            // QMessageBox::information(this,"faild","请求发送失败！");

         }
         // 处理响应
         connect(reply, &QModbusReply::finished, [reply,this]()
         {
             if (reply->error() == QModbusDevice::NoError)
             {
                 qDebug() << "写入成功AirHumidity!!!！";
                 //QMessageBox::information(this,"success","写入成功！");



             } else
             {
                 qDebug() << "错误：" << reply->errorString();
                 //  QMessageBox::information(this,"faild","失败！");

             }
             reply->deleteLater();
         });

}

void ModBusManger::setCO2(int step)
{
    extern QVector<sensorData> globalSensorData2;
    extern int totalCount2;
     AlarmIndex.Index_CO2++;
     if(AlarmIndex.Index_CO2==1)
     {
         if(totalCount2 > 1)
         {
              AlarmData.Data_CO2=globalSensorData2[totalCount2-1].CO2Concentration;
         }

         qDebug()<<"AlarmData.Data_CO2:"<<AlarmData.Data_CO2<<endl;
     }

     int tempData=AlarmData.Data_CO2+step*AlarmIndex.Index_CO2;
     qDebug()<<"tempData"<< ":"<<tempData<<endl;
     QModbusDataUnit request(QModbusDataUnit::HoldingRegisters,3,1);
     request.setValue(0,tempData);
     QModbusReply* reply = modbusDevice->sendWriteRequest(request, 1);
     if (!reply)
     {
         qDebug() << "请求发送失败";
        // QMessageBox::information(this,"faild","请求发送失败！");

     }
     // 处理响应
     connect(reply, &QModbusReply::finished, [reply,this]()
     {
         if (reply->error() == QModbusDevice::NoError)
         {
             qDebug() << "写入成功AirHumidity!!!！";
             //QMessageBox::information(this,"success","写入成功！");



         } else
         {
             qDebug() << "错误：" << reply->errorString();
             //  QMessageBox::information(this,"faild","失败！");

         }
         reply->deleteLater();
     });


}

void ModBusManger::setLight(int step)
{

    extern QVector<sensorData> globalSensorData2;
    extern int totalCount2;
     AlarmIndex.Index_Light++;
     if(AlarmIndex.Index_Light==1)
     {
         if(totalCount2 > 1)
         {
              AlarmData.Data_Light=globalSensorData2[totalCount2-1].LightIntensity;
         }

         qDebug()<<"AlarmData.Data_Light:"<<AlarmData.Data_Light<<endl;
     }

     int tempData=AlarmData.Data_Light+step*AlarmIndex.Index_Light;
     qDebug()<<"tempData"<< ":"<<tempData<<endl;
     QModbusDataUnit request(QModbusDataUnit::HoldingRegisters,2,1);
     request.setValue(0,tempData);
     QModbusReply* reply = modbusDevice->sendWriteRequest(request, 1);
     if (!reply)
     {
         qDebug() << "请求发送失败";
        // QMessageBox::information(this,"faild","请求发送失败！");

     }
     // 处理响应
     connect(reply, &QModbusReply::finished, [reply,this]()
     {
         if (reply->error() == QModbusDevice::NoError)
         {
             qDebug() << "写入成功AirHumidity!!!！";
             //QMessageBox::information(this,"success","写入成功！");



         } else
         {
             qDebug() << "错误：" << reply->errorString();
             //  QMessageBox::information(this,"faild","失败！");

         }
         reply->deleteLater();
     });

}

void ModBusManger::setSoilH(int step)
{

    extern QVector<sensorData> globalSensorData2;
    extern int totalCount2;
     AlarmIndex.Index_SoilH++;
     if(AlarmIndex.Index_SoilH==1)
     {
         if(totalCount2 > 1)
         {
              AlarmData.Data_SoilH=globalSensorData2[totalCount2-1].SoilMoisture;
         }

         qDebug()<<"AlarmData.Data_SoilH:"<<AlarmData.Data_SoilH<<endl;
     }

     int tempData=AlarmData.Data_SoilH+step*AlarmIndex.Index_SoilH;
     qDebug()<<"tempData"<< ":"<<tempData<<endl;
     QModbusDataUnit request(QModbusDataUnit::HoldingRegisters,4,1);
     request.setValue(0,tempData);
     QModbusReply* reply = modbusDevice->sendWriteRequest(request, 1);
     if (!reply)
     {
         qDebug() << "请求发送失败";
        // QMessageBox::information(this,"faild","请求发送失败！");

     }
     // 处理响应
     connect(reply, &QModbusReply::finished, [reply,this]()
     {
         if (reply->error() == QModbusDevice::NoError)
         {
             qDebug() << "写入成功SoilH!!!！";
             //QMessageBox::information(this,"success","写入成功！");



         } else
         {
             qDebug() << "错误：" << reply->errorString();
             //  QMessageBox::information(this,"faild","失败！");

         }
         reply->deleteLater();
     });

}

//int ModBusManger::getCurrentSingleSensorData(int address)
//{
// qDebug()<<"in->getCurrentSingleSensorData函数"<<endl;
//int currentData=0;
//QModbusDataUnit request(QModbusDataUnit::HoldingRegisters, 0, 1);
//// 发送请求到设备1
//QModbusReply* reply = modbusDevice->sendReadRequest(request, 1);

//if (!reply)
//{
//    qDebug() << "请求发送失败";
//    return currentData;
//}
//else
//{
//    qDebug()<<"in->else reply"<<endl;
//    connect(reply, &QModbusReply::finished, [reply,&currentData,this](){
//        if (reply->error() == QModbusDevice::NoError)
//        {
//            const QModbusDataUnit data = reply->result();
//            qDebug()<<"--进入data.value(0)--:"<<data.value(0);
//            currentData=data.value(0);
//        }});

//    reply->deleteLater();

//    return currentData;
//}

//}

void ModBusManger::resetAlarmIndexAndData(int index)
{
    switch(index)
    {
    case 0:
    {
        AlarmIndex.Index_AirT=0;
        AlarmData.Data_AirT=0;
    }
        break;
    case 1:
    {
        AlarmIndex.Index_AirH=0;
        AlarmData.Data_AirH=0;
    }
        break;
    case 2:
    {
        AlarmIndex.Index_Light=0;
        AlarmData.Data_Light=0;
    }
        break;
    case 3:
    {
        AlarmIndex.Index_CO2=0;
        AlarmData.Data_CO2=0;
    }
        break;
    case 4:
    {
        AlarmIndex.Index_SoilH=0;
        AlarmData.Data_SoilH=0;
    }
        break;
    }
}

void ModBusManger::autoSetAirTemperature()
{
    extern QVector<int>SetPointValueS;
//    int tempData=25;
    int tempData=SetPointValueS[0];
    QModbusDataUnit request(QModbusDataUnit::HoldingRegisters, 0, 1);
    request.setValue(0,tempData);
    QModbusReply* reply = modbusDevice->sendWriteRequest(request, 1);
    if (!reply)
    {
        qDebug() << "请求发送失败";
        // QMessageBox::information(this,"faild","请求发送失败！");

    }
    // 处理响应
    connect(reply, &QModbusReply::finished, [reply,this]()
    {
        if (reply->error() == QModbusDevice::NoError)
        {
            qDebug() << "写入成功AirT==25!!!！";
            //QMessageBox::information(this,"success","写入成功！");



        } else
        {
            qDebug() << "错误：" << reply->errorString();
            //  QMessageBox::information(this,"faild","失败！");

        }
        reply->deleteLater();
    });
}

void ModBusManger::autoSetAirHumidity()
{
    extern QVector<int>SetPointValueS;
//    int tempData=67;
    int tempData=SetPointValueS[1];
    QModbusDataUnit request(QModbusDataUnit::HoldingRegisters, 1, 1);
    request.setValue(0,tempData);
    QModbusReply* reply = modbusDevice->sendWriteRequest(request, 1);
    if (!reply)
    {
        qDebug() << "请求发送失败";
        // QMessageBox::information(this,"faild","请求发送失败！");

    }
    // 处理响应
    connect(reply, &QModbusReply::finished, [reply,this]()
    {
        if (reply->error() == QModbusDevice::NoError)
        {
            qDebug() << "写入成功Light==35!!!！";
            //QMessageBox::information(this,"success","写入成功！");



        } else
        {
            qDebug() << "错误：" << reply->errorString();
            //  QMessageBox::information(this,"faild","失败！");

        }
        reply->deleteLater();
    });
}

void ModBusManger::autoSetLight()
{

    extern QVector<int>SetPointValueS;
    int tempData=SetPointValueS[2];
//     int tempData=35;
    QModbusDataUnit request(QModbusDataUnit::HoldingRegisters, 2, 1);
    request.setValue(0,tempData);
    QModbusReply* reply = modbusDevice->sendWriteRequest(request, 1);
    if (!reply)
    {
        qDebug() << "请求发送失败";
        // QMessageBox::information(this,"faild","请求发送失败！");

    }
    // 处理响应
    connect(reply, &QModbusReply::finished, [reply,this]()
    {
        if (reply->error() == QModbusDevice::NoError)
        {
            qDebug() << "写入成功Light==35!!!！";
            //QMessageBox::information(this,"success","写入成功！");



        } else
        {
            qDebug() << "错误：" << reply->errorString();
            //  QMessageBox::information(this,"faild","失败！");

        }
        reply->deleteLater();
    });
}

void ModBusManger::autoSetCO2()
{
    extern QVector<int>SetPointValueS;
    int tempData=SetPointValueS[3];
//    int tempData=1150;
    QModbusDataUnit request(QModbusDataUnit::HoldingRegisters, 3, 1);
    request.setValue(0,tempData);
    QModbusReply* reply = modbusDevice->sendWriteRequest(request, 1);
    if (!reply)
    {
        qDebug() << "请求发送失败";
        // QMessageBox::information(this,"faild","请求发送失败！");

    }
    // 处理响应
    connect(reply, &QModbusReply::finished, [reply,this]()
    {
        if (reply->error() == QModbusDevice::NoError)
        {
            qDebug() << "写入成功Light==35!!!！";
            //QMessageBox::information(this,"success","写入成功！");



        } else
        {
            qDebug() << "错误：" << reply->errorString();
            //  QMessageBox::information(this,"faild","失败！");

        }
        reply->deleteLater();
    });
}

void ModBusManger::autoSetSoilH()
{
    extern QVector<int>SetPointValueS;
    int tempData=SetPointValueS[4];
//    int tempData=72;
    QModbusDataUnit request(QModbusDataUnit::HoldingRegisters, 4, 1);
    request.setValue(0,tempData);
    QModbusReply* reply = modbusDevice->sendWriteRequest(request, 1);
    if (!reply)
    {
        qDebug() << "请求发送失败";
        // QMessageBox::information(this,"faild","请求发送失败！");

    }
    // 处理响应
    connect(reply, &QModbusReply::finished, [reply,this]()
    {
        if (reply->error() == QModbusDevice::NoError)
        {
            qDebug() << "写入成功Light==35!!!！";
            //QMessageBox::information(this,"success","写入成功！");



        } else
        {
            qDebug() << "错误：" << reply->errorString();
            //  QMessageBox::information(this,"faild","失败！");

        }
        reply->deleteLater();
    });
}




